package com.hfqby.camera.framework.websocket;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.BlockingQueue;

/**
 * websocket数据
 *
 * @author qiu bo yang
 * @date 2023-08-09 10:28
 */
public class BlockQueue {
    public static Map<String, String> sessionToUserIdMap = new HashMap<>();

    public static Map<String, String> playToUserIdMap = new HashMap<>();

    public static Map<String, String> ipToUserIdMap = new HashMap<>();

    public static Map<String, BlockingQueue> bqMap = new HashMap<>();

    /**
     * 通过摄像头登录句柄进行数据清理
     *
     * @param userId 登录id
     */
    public static void clearUserId(String userId, boolean logout) {
        if (BlockQueue.bqMap == null) {
            System.out.println("bqMap为空");
            BlockQueue.bqMap = new HashMap<>();
        }
        if (BlockQueue.playToUserIdMap == null) {
            System.out.println("playToUserIdMap为空");
            BlockQueue.playToUserIdMap = new HashMap<>();
        }
        if (BlockQueue.sessionToUserIdMap == null) {
            System.out.println("sessionToUserIdMap为空");
            BlockQueue.sessionToUserIdMap = new HashMap<>();
        }

        for (String key : BlockQueue.playToUserIdMap.keySet()) {
            String value = BlockQueue.playToUserIdMap.get(key);
            if (userId.equals(value)) {
                BlockQueue.playToUserIdMap.remove(key);
                break;
            }
        }

        for (String key : BlockQueue.sessionToUserIdMap.keySet()) {
            String value = BlockQueue.sessionToUserIdMap.get(key);
            if (userId.equals(value)) {
                BlockQueue.sessionToUserIdMap.remove(key);
                break;
            }
        }

        if (logout) {
            for (String key : BlockQueue.ipToUserIdMap.keySet()) {
                String value = BlockQueue.ipToUserIdMap.get(key);
                if (userId.equals(value)) {
                    BlockQueue.ipToUserIdMap.remove(key);
                    break;
                }
            }
        }

    }

    /**
     * 通过ip查询是否正在登录或者预览
     *
     * @param ip ip信息
     */
    public static String findUserIdByIp(String ip) {
        for (String key : BlockQueue.ipToUserIdMap.keySet()) {
            String value = BlockQueue.ipToUserIdMap.get(key);
            if (ip.equals(key)) {
                return value;
            }
        }
        return "";
    }

    /**
     * 通过摄像头登录句柄查询当前用户是否正在预览
     *
     * @param userId 登录id
     */
    public static String findPlayIdByUserId(String userId) {
        for (String key : BlockQueue.playToUserIdMap.keySet()) {
            String value = BlockQueue.playToUserIdMap.get(key);
            if (userId.equals(value)) {
                return key;
            }
        }
        return "";
    }
}
